package com.xxx.sso.base;

import com.xxx.sso.util.Result;
import com.xxx.sso.util.ResultBuilder;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 基础Ctrl，同基础Service
 * @author caiwl
 * @date 2020/5/11 15:30
 */
public abstract class BaseCtrl<T extends BaseEntity> {

    /**
     * 条件+分页查询
     * @param page
     * @return
     */
    @GetMapping
    public Result page(T probe, @PageableDefault Pageable page) {
        return ResultBuilder.okWithPage(service().page(probe, page));
    }

    /**
     * 单个查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result getOne(@PathVariable("id") Long id) {
        return ResultBuilder.okWithObj(service().getOne(id));
    }

    /**
     * 新增
     * @param entity
     * @return
     */
    @PostMapping
    public Result add(@Validated T entity) {
        return ResultBuilder.okWithObj(service().add(entity));
    }

    /**
     * 修改
     * @param entity
     * @return
     */
    @PutMapping("/{id}")
    public Result update(@PathVariable("id") Long id, @Validated T entity) {
        service().update(id, entity);
        return ResultBuilder.ok();
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Long id) {
        service().delete(id);
        return ResultBuilder.ok();
    }

    /**
     * 获取注入的Service
     * @return
     */
    protected abstract BaseService<T> service();
}
